﻿Imports System.IO
Imports System.Net
Imports System.Text

Public Class Main

    Private Sub txtCommand_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCommand.KeyDown
        If e.KeyCode = Keys.Enter Then
            Exec(txtCommand.Text)
        End If
    End Sub

    Function Exec(ByVal Command As String) As Boolean
        Dim Result As Boolean = False
        txtCommand.Text = "Loading"
        txtCommand.Enabled = False

        Command = Command.Replace("[[DW]]", Today.DayOfWeek.ToString)

        Dim rCommand As String = Command.ToLower
        If Command.Split(" ").Length > 0 Then
            rCommand = Command.Split(" ")(0).ToLower
        End If
        Dim ReturnValue As String = "OK"

        Select Case rCommand
            Case "clear"
                lstCommand.Items.Clear()
            Case "validateurl"
                If Command.Split(" ").Length = 2 Then
                    Dim url As String = Command.Split(" ")(1)
                    Dim waitingLimit = 0
                    Do

                        waitingLimit = waitingLimit + 1
                        AddCommandList("Waiting..." + waitingLimit.ToString)
                        WaitUntilPageLoadComplete()
                        Threading.Thread.Sleep(500)
                        Application.DoEvents()
                    Loop Until wb.Url.ToString = url Or waitingLimit = 5
                    If Not wb.Url.ToString = url Then
                        ReturnValue = "Expected " + url + " but detected " + wb.Url.ToString
                    End If
                End If
            Case "load"
                If Command.Split(" ").Length = 2 Then
                    Dim filename As String = Command.Split(" ")(1)
                    Dim IO As TextReader = New StreamReader(filename)
                    Dim command_line As String
                    Do
                        command_line = IO.ReadLine()
                        txtCommand.Text = command_line
                        If Not command_line Is Nothing Then
                            If Not Exec(command_line) Then
                                command_line = Nothing
                            End If
                            Application.DoEvents()
                        End If
                    Loop Until command_line Is Nothing
                    IO.Close()
                Else
                    AddCommandList("Not enough parameter. You need to enter [filename] that you wish to load")
                End If
            Case "go"
                Dim url As String = Microsoft.VisualBasic.Right(Command, Len(Command) - Len(rCommand)).Trim
                wb.Navigate(url)
                AddCommandList("Loading website....")
                WaitUntilPageLoadComplete()

            Case "list"

                AddCommandList("---- List of input ----")
                If Command.Split(" ").Length >= 2 Then
                    ' second value would be the filter
                    Dim filter As String = Command.Split(" ")(1)
                    Dim specialCmd As String = ""
                    Dim SA As New StringBuilder
                    If Command.Split(" ").Length = 3 Then
                        specialCmd = Command.Split(" ")(2)
                    End If
                    For Each link As HtmlElement In wb.Document.Links



                        If link.GetAttribute("href").Contains(filter) Then
                            AddCommandList(link.GetAttribute("href"))
                            If specialCmd.ToLower = "c" Then
                                SA.AppendFormat("{0}", link.GetAttribute("href")).AppendLine()
                            End If
                        End If
                    Next
                    If specialCmd.ToLower = "c" Then
                        Clipboard.SetText(SA.ToString)
                    End If
                Else
                    ' if no parameter, use default
                    For Each HE As HtmlElement In wb.Document.GetElementsByTagName("input")
                        If Not HE.Id Is Nothing Then
                            AddCommandList(HE.Id)
                        End If
                    Next

                    For Each link As HtmlElement In wb.Document.Links
                        'AddCommandList(link.InnerHtml)

                        AddCommandList(link.GetAttribute("href"))
                    Next
                End If
            Case "url"
                AddCommandList(wb.Url.ToString)
            Case "launch"
                If Command.Split(" ").Length = 2 Then

                    Dim filename As String = Command.Split(" ")(1)
                    AddCommandList("Waiting for program to exit...")
                    Dim myProcess As Process = System.Diagnostics.Process.Start(filename)

                    While Not myProcess.HasExited
                        Threading.Thread.Sleep(1000)
                        Application.DoEvents()

                    End While
                Else
                    AddCommandList("Not enough parameter. You need to enter [filename] that you wish to load")
                End If
            Case "click"
                If Command.Split(" ").Length = 2 Then
                    Dim ID As String = Command.Split(" ")(1)
                    wb.Document.GetElementById(ID).InvokeMember("click")
                    Threading.Thread.Sleep(1500)
                    WaitUntilPageLoadComplete()
                Else
                    ReturnValue = "Not enough parameter. You need to enter [ID]"
                End If
            Case "download"
                If Command.Split(" ").Length = 3 Then
                    Dim filename As String = Command.Split(" ")(1)
                    Dim savePath As String = Command.Split(" ")(2)
                    Dim wc As New WebClient
                    AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressCallback

                    wc.DownloadFileAsync(New Uri(filename), savePath)
                    AddCommandList("Downloading....")

                    While wc.IsBusy

                        Threading.Thread.Sleep(1000)
                        Application.DoEvents()

                    End While
                    AddCommandList("Download completed")
                    'wb.Document.GetElementById(ID).InvokeMember("click")
                    'Threading.Thread.Sleep(1500)
                    'WaitUntilPageLoadComplete()
                Else
                    ReturnValue = "Not enough parameter. You need to enter [url] to download the file and [savePath] on where you want to save"
                End If

            Case ("enter")
                If Command.Split(" ").Length = 3 Then
                    Dim ID As String = Command.Split(" ")(1)
                    Dim Value As String = Command.Split(" ")(2)
                    wb.Document.GetElementById(ID).SetAttribute("value", Value)
                Else
                    ReturnValue = "Not enough parameter. You need to enter [ID] and [Value]"
                End If
            Case "exit"
                Application.Exit()
            Case Else
                ReturnValue = "NOT VALID"
        End Select

        AddCommandList(Command + " - " + ReturnValue)
        If ReturnValue = "OK" Then
            Result = True
        End If
        'lstCommand.SelectedIndex = lstCommand.Items.Count - 1
        txtCommand.Text = ""
        txtCommand.Enabled = True
        txtCommand.Focus()
        Return Result
    End Function

    Private Sub DownloadProgressCallback(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)

        '  Displays the operation identifier, and the transfer progress.
        'Console.WriteLine("0}    downloaded 1} of 2} bytes. 3} % complete...", _
        ' CStr(e.UserState), e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage)
        AddCommandList(CStr(e.UserState) + "      downloaded " + e.BytesReceived.ToString + " of " + e.TotalBytesToReceive.ToString + ". " + e.ProgressPercentage.ToString + " complete...")

    End Sub


    Sub WaitUntilPageLoadComplete()
        Dim StatusText As String = ""
        'While (wb.StatusText.ToLower <> "done")
        AddCommandList("Detected current state: " + wb.ReadyState.ToString)
        While (wb.ReadyState <> WebBrowserReadyState.Complete Or wb.IsBusy = True)

            If (wb.StatusText.ToLower <> "done" And wb.StatusText <> "") Then
                If wb.StatusText.ToLower <> StatusText Then
                    AddCommandList(wb.StatusText)
                    'lstCommand.SelectedIndex = lstCommand.Items.Count - 1
                    StatusText = wb.StatusText.ToLower
                End If
            End If

            Application.DoEvents()
        End While
    End Sub

    Public Sub AddCommandList(ByVal Command As String, Optional ByVal HiddenCommand As String = "")

        lstCommand.Items.Add(Command)
        'lstCommand.Items(lstCommand.Items.Count - 1).
        lstCommand.SelectedIndex = lstCommand.Items.Count - 1
    End Sub


    Private Sub lstCommand_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstCommand.MouseDoubleClick
        If lstCommand.SelectedIndex > 0 Then
            txtCommand.Text = txtCommand.Text + lstCommand.Items(lstCommand.SelectedIndex).ToString
        End If
    End Sub

    Private Sub Main_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Private Sub Main_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint

    End Sub

    Private Sub Main_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        Dim args As String() = Environment.GetCommandLineArgs
        args(0) = "clear"
        For Each arg As String In args
            Application.DoEvents()

            If Not Exec(arg) Then
                Application.Exit()
            End If
        Next
    End Sub
End Class
